<?php

namespace App\Http\Controllers\System;

use App\Criteria\System\User\UserBaseQueryCriteria;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CurlRecordMethod;
use App\Http\Requests\System\UserRequest;
use App\Libs\Tools\SystemCodeConstant;
use App\Models\System\Mo\UserExcelImportMO;
use App\Repositories\Personnel\DepartmentRepository;
use App\Repositories\Personnel\StationRepository;
use App\Repositories\System\UserRepository;
use App\Validators\System\UserValidator;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;

class UsersController extends Controller
{
    use CurlRecordMethod;

    protected $index_page='system.user.userMain';
    protected $add_page='system.user.userAdd';
    protected $edit_page='system.user.userEdit';

    protected $repository;
    protected $validator;
    protected $request;

    protected $departmentRepository;
    protected $stationRepository;

    public function __construct(UserRepository $repository,
                                DepartmentRepository $departmentRepository,
                                StationRepository $stationRepository,
                                UserValidator $validator, UserRequest $request){
        $this->repository = $repository;
        $this->validator  = $validator;
        $this->request    = $request;
        $this->departmentRepository=$departmentRepository;
        $this->stationRepository=$stationRepository;
    }

    public function getBaseQueryCriteria(){
        return new UserBaseQueryCriteria;
    }

    protected function get_add_data(){
//       $users=$this->repository->all();
       $departments=$this->departmentRepository->all();
       $stations=$this->stationRepository->all();
       return view($this->add_page,compact('departments','stations'));
    }

    protected function post_add_data(){
        try {
            $this->validator->with($this->request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);
            DB::transaction(function () {
                $all=$this->wrap_user_info($this->request->all(),true);
                $all['password']=bcrypt($all['password']);
                $model=$this->repository->skipPresenter()->create($all);


                $user_departments=array();
                if(isset($all['assist_department_ids'])){
                    $department_ids=$all['assist_department_ids'];
                    foreach ($department_ids as $key=>$department_id){
                        array_push($user_departments,['created_user'=>$model->created_user,'department_id'=>$department_id,'type'=>SystemCodeConstant::USER_DEPARTMENT_TYPE_ASSIST]);
                    }
                }
                if($model->major_department_id!='0'){
                    array_push($user_departments,['created_user'=>$model->created_user,'department_id'=>$model->major_department_id,'type'=>SystemCodeConstant::USER_DEPARTMENT_TYPE_MAJOR]);
                }
                $this->repository->skipPresenter()->sync($model->id, 'departments', $user_departments);


                $user_stations=array();
                if(isset($all['assist_station_ids'])){
                    $station_ids=$all['assist_station_ids'];
                    foreach ($station_ids as $key=>$station_id){
                        array_push($user_stations,['created_user'=>$model->created_user,'station_id'=>$station_id,'type'=>SystemCodeConstant::USER_STATION_TYPE_ASSIST]);
                    }
                }
                if($model->major_station_id!='0'){
                    array_push($user_stations,['created_user'=>$model->created_user,'station_id'=>$model->major_station_id,'type'=>SystemCodeConstant::USER_STATION_TYPE_MAJOR]);
                }
                $this->repository->skipPresenter()->sync($model->id, 'stations', $user_stations);
                $this->repository->refreshPermission($model->id);

            });
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

    protected function get_edit_data(){
//        $users=$this->repository->all();
        $departments=$this->departmentRepository->all();
        $stations=$this->stationRepository->all();
        $id=$this->request->get('id');
        $editEntity = $this->repository->skipPresenter()->with(['departments','stations'])->find($id);
        return view($this->edit_page,compact('departments','stations','editEntity'));
    }

    protected function post_edit_data(){
        try {
            $this->validator->with($this->request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);
            DB::transaction(function () {
                $all=$this->wrap_user_info($this->request->all());
                if(empty($all['password'])){unset($all['password']);}else{
                    $all['password']=bcrypt($all['password']);
                }
                $id=$this->request->get('id');
                $model=$this->repository->skipPresenter()->update($all, $id);


                $user_departments=[];
                $this->repository->skipPresenter()->sync($model->id, 'departments', $user_departments);
                if(isset($all['assist_department_ids'])){
                    $department_ids=$all['assist_department_ids'];
                    foreach ($department_ids as $key=>$department_id){
                        array_push($user_departments,['created_user'=>$model->created_user,'department_id'=>$department_id,'type'=>SystemCodeConstant::USER_DEPARTMENT_TYPE_ASSIST]);
                    }
                }
                if($model->major_department_id!='0'){
                    array_push($user_departments,['created_user'=>$model->created_user,'department_id'=>$model->major_department_id,'type'=>SystemCodeConstant::USER_DEPARTMENT_TYPE_MAJOR]);
                }
                $this->repository->skipPresenter()->sync($model->id, 'departments', $user_departments);


                $user_stations=[];
                $this->repository->skipPresenter()->sync($model->id, 'stations', $user_stations);
                if(isset($all['assist_station_ids'])){
                    $station_ids=$all['assist_station_ids'];
                    foreach ($station_ids as $key=>$station_id){
                        array_push($user_stations,['created_user'=>$model->created_user,'station_id'=>$station_id,'type'=>SystemCodeConstant::USER_STATION_TYPE_ASSIST]);
                    }
                }
                if($model->major_station_id!='0'){
                    array_push($user_stations,['created_user'=>$model->created_user,'station_id'=>$model->major_station_id,'type'=>SystemCodeConstant::USER_STATION_TYPE_MAJOR]);
                }
                $this->repository->skipPresenter()->sync($model->id, 'stations', $user_stations);
                $this->repository->refreshPermission($model->id);
            });

            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

    public function delete_data(){
        $id=Input::get('id');
        $model=$this->repository->skipPresenter()->find($id);
        if(!$model->isLeave()){
            return $this->return_json_error_message($model->name.'不能被删除；只有离职用户才能被删除');
        }
        DB::transaction(function () {
            $id=Input::get('id');
            $model=$this->repository->skipPresenter()->find($id);
            //移除辅助岗位身份
            $model->stations()->detach();
            //移除辅助部门身份
            $model->departments()->detach();
            $this->repository->delete($id);
        });
        return $this->return_json_success();
    }

    public function updateStatus(){
        $ids=Input::get('ids');
        $account_status=Input::get('account_status');
        $models=$this->repository->skipPresenter()->findWhereIn('id',$ids);
        foreach ($models as $model){
            $models->updated_user=Auth::user()['name'];
            $model->account_status=$account_status;
            $model->save();
        }
        return $this->return_json_success();
    }


    public function deleteStation(){
        DB::transaction(function () {
            $ids=Input::get('ids');
            $station_id=Input::get('station_id');
            $models=$this->repository->skipPresenter()->findWhereIn('id',$ids);
            $updated_user=Auth::user()['name'];
            foreach ($models as $model){
                if($model->major_station_id==$station_id){
                    $model->major_station_id=0;
                    $model->updated_user=$updated_user;
                    $model->save();
                }
                $model->stations()->detach($station_id);
            }
        });
        return $this->return_json_success();
    }

    public function addStation(){
        DB::transaction(function () {
            $station_id=Input::get('station_id');
            $ids=Input::get('ids');
            $models=$this->repository->skipPresenter()->findWhereIn('id',$ids);
            $created_user=Auth::user()['name'];
            foreach ($models as $model){
                $model->stations()->attach($station_id,['created_user'=>$created_user,'type'=>SystemCodeConstant::USER_STATION_TYPE_ASSIST]);
            }
        });
        return $this->return_json_success();
    }

    public function password_edit(Hasher $hasher){
        try {
            $id=Input::get('id');
            $this->validator->with($this->request->all())->passesOrFail('UPDATE_PASSWORD_WITH_ID');
            $user=$this->repository->skipPresenter()->find($id);
            $result=$hasher->check(Input::get('old_password'),$user->password);
            if(!$result){
                return $this->return_json_error_message('原密码错误');
            }
            $user->password=bcrypt(Input::get('password'));
            $user->updated_user=Auth::user()['name'];
            $user->save();
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

    public function import(){
        $reader=Excel::load(Input::file('file'));
        $reader = $reader->ignoreEmpty()->getSheet(0);
        $res = $reader->toArray();
        if(count($res)<1){
            return $this->return_json_error_message('空excel');
        }
        $userExcelImport=new UserExcelImportMO();
        $errorMsg=$userExcelImport->convert($res)->verify();
        if($errorMsg!=null){
            return $this->return_json_error_message($errorMsg);
        }
        $errorMsg=$userExcelImport->convert_results_data();
        if($errorMsg!=null){
            return $this->return_json_error_message($errorMsg);
        }
        DB::transaction(function () use(&$userExcelImport) {
            $results=$userExcelImport->getResults();
            foreach ($results as $key=>$result){
                $result=$this->wrap_user_info($result,true);
                $model=$this->repository->skipPresenter()->create($result);

                $user_departments=array();
                if($model->major_department_id!='0'){
                    array_push($user_departments,['created_user'=>$model->created_user,'department_id'=>$model->major_department_id,'type'=>SystemCodeConstant::USER_DEPARTMENT_TYPE_MAJOR]);
                }
                $this->repository->skipPresenter()->sync($model->id, 'departments', $user_departments);


                $user_stations=[];
                $this->repository->skipPresenter()->sync($model->id, 'stations', $user_stations);
                if($model->major_station_id!='0'){
                    array_push($user_stations,['created_user'=>$model->created_user,'station_id'=>$model->major_station_id,'type'=>SystemCodeConstant::USER_STATION_TYPE_MAJOR]);
                }
                $this->repository->skipPresenter()->sync($model->id, 'stations', $user_stations);
            }
        });
        return $this->return_json_success();
    }
}
